package com.xxx.netty.eventloop;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringEncoder;
import lombok.extern.slf4j.Slf4j;

import java.net.InetSocketAddress;

/**
 * EventLoop Future Client端
 */
@Slf4j
public class EventLoopFutureClient {

    public static void main(String[] args) throws InterruptedException {
        // ChannelFuture Client端启动入口
        ChannelFuture channelFuture = new Bootstrap()
                .group(new NioEventLoopGroup())
                .channel(NioSocketChannel.class)
                .handler(new ChannelInitializer<NioSocketChannel>() {
                    @Override
                    protected void initChannel(NioSocketChannel ch) throws Exception {
                        ch.pipeline().addLast(new StringEncoder());
                    }
                })
                .connect(new InetSocketAddress("localhost", 8080));

        // 方式1：同步方式，主线程需要阻塞，等待NioEventLoopGroup中的线程将Client与Server连接建立完成
//        channelFuture.sync();  // 主线程需要阻塞
//        Channel channel = channelFuture.channel();
//        log.info("channel:{}", channel);
//        channel.writeAndFlush("hello");

        // 方式2：异步方式，通过addListener()，给NioEventLoopGroup中的线程添加监听器，由NioEventLoopGroup中的线程来进行操作
        channelFuture.addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture channelFuture) throws Exception {
                Channel channel = channelFuture.channel();
                log.info("channel:{}", channel);
                channel.writeAndFlush("hello");
            }
        });
    }
}
